package util;

import javafx.util.Pair;
import vo.StockInfo;

public class StockSorterImpl implements StockSorter {
	/**
	 * Accepting series of stock info, sorting them ascending according to their
	 * comment length. List.sort() or Arrays.sort() are not allowed. You have to
	 * write your own algorithms,Bubble sort、quick sort、merge sort、select sort,etc.
	 *
	 * @param info
	 *            stock information
	 * @return sorted stock
	 */
	@Override
	public StockInfo[] sort(StockInfo[] info) {
		// TODO: write your code here
		for (int i = 0; i < info.length; i++) {
			for (int j = 0; j < info.length - 1 - i; j++) {
				if (info[j].getANSWER().length() > info[j + 1].getANSWER().length()) {
					StockInfo temp;
					temp = info[j];
					info[j] = info[j + 1];
					info[j + 1] = temp;
				}
			}
		}
		return info;
	}

	/**
	 * Accepting series of stock info, sorting them ascending, descending order.
	 *
	 * @param info
	 *            stock information
	 * @param order
	 *            true:ascending,false:descending
	 * @return sorted stock
	 */
	@Override
	public StockInfo[] sort(StockInfo[] info, boolean order) {
		// TODO: write your code here
		if (order) {
			for (int i = 0; i < info.length; i++) {
				for (int j = 0; j < info.length - 1 - i; j++) {
					if (info[j].getANSWER().length() > info[j + 1].getANSWER().length()) {
						StockInfo temp;
						temp = info[j];
						info[j] = info[j + 1];
						info[j + 1] = temp;
					}
				}
			}
		} else {
			for (int i = 0; i < info.length; i++) {
				for (int j = 0; j < info.length - 1 - i; j++) {
					if (info[j].getANSWER().length() < info[j + 1].getANSWER().length()) {
						StockInfo temp;
						temp = info[j];
						info[j] = info[j + 1];
						info[j + 1] = temp;
					}
				}
			}
		}
		return info;
	}

	/**
	 * 对Pair<String,Double>数组进行降序排列
	 * 
	 * @param pairArray
	 * @return
	 */
	public Pair<String, Double>[] sort(Pair<String, Double>[] pairArray) {
		for (int i = 0; i < pairArray.length; i++) {
			for (int j = 0; j < pairArray.length - 1 - i; j++) {
				if (pairArray[j].getValue() < pairArray[j + 1].getValue()) {
					Pair<String, Double> temp;
					temp = pairArray[j];
					pairArray[j] = pairArray[j + 1];
					pairArray[j + 1] = temp;
				}
			}
		}
		return pairArray;
	}
}
